#include "dtu_web.h"
#include "dtu_log.h"
#include "dtu_memory.h"
#include "dtu_config.h"
#include "dtu_modbus.h"
#include "dtu_network.h"
#include "dtu_at_command.h"
#include "dtu_data_collect.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/stat.h>

/* 全局Web服务器 */
static web_server_t g_web_server = {0};

/* 获取Web UI目录路径 */
static void get_web_ui_path(char* path, size_t size) {
    /* 尝试多个可能的路径 */
    const char* possible_paths[] = {
        "./web_ui",                    /* 当前目录下 */
        "../web_ui",                   /* 上级目录下 */
        "../../web_ui",                /* 上两级目录下 */
        "/Users/yangzhenguo/workspace_python/iot-dtu-c/web_ui"  /* 绝对路径 */
    };

    for (size_t i = 0; i < sizeof(possible_paths) / sizeof(possible_paths[0]); i++) {
        struct stat st;
        char test_path[512];
        snprintf(test_path, sizeof(test_path), "%s/index.html", possible_paths[i]);

        if (stat(test_path, &st) == 0) {
            strncpy(path, possible_paths[i], size - 1);
            path[size - 1] = '\0';
            return;
        }
    }

    /* 如果都找不到，使用默认路径 */
    strncpy(path, "./web_ui", size - 1);
    path[size - 1] = '\0';
}

/* 默认Web配置 */
static web_config_t default_web_config = {
    .port = DTU_WEB_PORT,
    .bind_address = "0.0.0.0",
    .max_connections = 10,
    .timeout = 30,
    .enable_auth = true,
    .username = "admin",
    .password = "admin123",
    .session_timeout = 3600,
    .document_root = "./web_ui",  /* 将在初始化时动态设置 */
    .enable_ssl = false,
    .ssl_cert = "",
    .ssl_key = ""
};

/* HTTP状态码描述 */
static const struct {
    http_status_t code;
    const char* description;
} http_status_descriptions[] = {
    {HTTP_STATUS_OK, "OK"},
    {HTTP_STATUS_CREATED, "Created"},
    {HTTP_STATUS_NO_CONTENT, "No Content"},
    {HTTP_STATUS_BAD_REQUEST, "Bad Request"},
    {HTTP_STATUS_UNAUTHORIZED, "Unauthorized"},
    {HTTP_STATUS_FORBIDDEN, "Forbidden"},
    {HTTP_STATUS_NOT_FOUND, "Not Found"},
    {HTTP_STATUS_METHOD_NOT_ALLOWED, "Method Not Allowed"},
    {HTTP_STATUS_INTERNAL_ERROR, "Internal Server Error"},
    {HTTP_STATUS_NOT_IMPLEMENTED, "Not Implemented"},
    {HTTP_STATUS_SERVICE_UNAVAILABLE, "Service Unavailable"}
};

/* HTTP方法字符串 */
static const char* http_method_strings[] = {
    "GET", "POST", "PUT", "DELETE", "OPTIONS"
};

/* 内部函数声明 */
static void* web_server_thread(void* arg);
static void handle_client_connection(int client_socket);
static dtu_error_t parse_http_request(const char* request_data, http_request_t* request);
static dtu_error_t find_route_handler(const http_request_t* request, route_item_t** route);
static void send_http_response(int client_socket, const http_response_t* response);
static void send_static_file(int client_socket, const char* file_path);
static void send_error_response(int client_socket, http_status_t status, const char* message);
static char* generate_session_id(void);
static void free_routes(void);
static void free_sessions(void);

/* API处理器声明 */
static dtu_error_t api_status_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_config_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_network_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_serial_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_collect_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_collect_start_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_collect_stop_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_modbus_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_modbus_test_config_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_modbus_test_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_push_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_system_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_system_info_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_system_save_config_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_system_clear_logs_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_system_check_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_serial_test_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_push_test_connection_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_push_test_data_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_at_command_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_login_handler(const http_request_t* request, http_response_t* response, void* user_data);
static dtu_error_t api_logout_handler(const http_request_t* request, http_response_t* response, void* user_data);

/* 辅助函数声明 */
static char* get_json_string_value(const char* json, const char* key);
static int get_json_int_value(const char* json, const char* key, int default_value);
static bool get_json_bool_value(const char* json, const char* key, bool default_value);
static void json_escape_string(const char* input, char* output, size_t output_size);

dtu_error_t dtu_web_init(const web_config_t* config)
{
    if (g_web_server.initialized) {
        return DTU_OK;
    }

    memset(&g_web_server, 0, sizeof(web_server_t));

    /* 使用提供的配置或默认配置 */
    if (config) {
        g_web_server.config = *config;
    } else {
        /* 动态检测web_ui目录路径 */
        get_web_ui_path(default_web_config.document_root, sizeof(default_web_config.document_root));
        g_web_server.config = default_web_config;
        DTU_LOG_INFO("Web UI document root set to: %s", g_web_server.config.document_root);
    }

    /* 初始化互斥锁 */
    if (pthread_mutex_init(&g_web_server.mutex, NULL) != 0) {
        return DTU_ERROR;
    }

    g_web_server.server_socket = -1;
    g_web_server.initialized = true;

    /* 注册默认API路由 */
    dtu_web_register_handler("/api/status", HTTP_METHOD_GET, api_status_handler, NULL);
    dtu_web_register_handler("/api/config", HTTP_METHOD_GET, api_config_handler, NULL);
    dtu_web_register_handler("/api/config", HTTP_METHOD_POST, api_config_handler, NULL);
    dtu_web_register_handler("/api/network", HTTP_METHOD_GET, api_network_handler, NULL);
    dtu_web_register_handler("/api/network", HTTP_METHOD_POST, api_network_handler, NULL);
    dtu_web_register_handler("/api/serial", HTTP_METHOD_GET, api_serial_handler, NULL);
    dtu_web_register_handler("/api/serial", HTTP_METHOD_POST, api_serial_handler, NULL);
    dtu_web_register_handler("/api/collect", HTTP_METHOD_GET, api_collect_handler, NULL);
    dtu_web_register_handler("/api/collect", HTTP_METHOD_POST, api_collect_handler, NULL);
    dtu_web_register_handler("/api/collect/start", HTTP_METHOD_POST, api_collect_start_handler, NULL);
    dtu_web_register_handler("/api/collect/stop", HTTP_METHOD_POST, api_collect_stop_handler, NULL);
    dtu_web_register_handler("/api/modbus", HTTP_METHOD_GET, api_modbus_handler, NULL);
    dtu_web_register_handler("/api/modbus", HTTP_METHOD_POST, api_modbus_handler, NULL);
    dtu_web_register_handler("/api/modbus-test", HTTP_METHOD_GET, api_modbus_test_config_handler, NULL);
    dtu_web_register_handler("/api/modbus-test", HTTP_METHOD_POST, api_modbus_test_config_handler, NULL);
    dtu_web_register_handler("/api/modbus/test", HTTP_METHOD_POST, api_modbus_test_handler, NULL);
    dtu_web_register_handler("/api/push", HTTP_METHOD_GET, api_push_handler, NULL);
    dtu_web_register_handler("/api/push", HTTP_METHOD_POST, api_push_handler, NULL);
    dtu_web_register_handler("/api/system", HTTP_METHOD_GET, api_system_handler, NULL);
    dtu_web_register_handler("/api/system", HTTP_METHOD_POST, api_system_handler, NULL);
    dtu_web_register_handler("/api/system/info", HTTP_METHOD_GET, api_system_info_handler, NULL);
    dtu_web_register_handler("/api/system/save-config", HTTP_METHOD_POST, api_system_save_config_handler, NULL);
    dtu_web_register_handler("/api/system/clear-logs", HTTP_METHOD_POST, api_system_clear_logs_handler, NULL);
    dtu_web_register_handler("/api/system/check", HTTP_METHOD_POST, api_system_check_handler, NULL);
    dtu_web_register_handler("/api/serial/test", HTTP_METHOD_POST, api_serial_test_handler, NULL);
    dtu_web_register_handler("/api/push/test-connection", HTTP_METHOD_POST, api_push_test_connection_handler, NULL);
    dtu_web_register_handler("/api/push/test-data", HTTP_METHOD_POST, api_push_test_data_handler, NULL);
    dtu_web_register_handler("/api/at-command", HTTP_METHOD_POST, api_at_command_handler, NULL);
    dtu_web_register_handler("/api/login", HTTP_METHOD_POST, api_login_handler, NULL);
    dtu_web_register_handler("/api/logout", HTTP_METHOD_POST, api_logout_handler, NULL);

    DTU_LOG_INFO("Web server initialized on port %d", g_web_server.config.port);
    return DTU_OK;
}

void dtu_web_cleanup(void)
{
    if (!g_web_server.initialized) {
        return;
    }

    /* 停止服务器 */
    dtu_web_stop();

    pthread_mutex_lock(&g_web_server.mutex);

    /* 释放路由和会话 */
    free_routes();
    free_sessions();

    g_web_server.initialized = false;

    pthread_mutex_unlock(&g_web_server.mutex);
    pthread_mutex_destroy(&g_web_server.mutex);

    DTU_LOG_INFO("Web server cleanup completed");
}

dtu_error_t dtu_web_start(void)
{
    if (!g_web_server.initialized) {
        return DTU_ERROR;
    }

    pthread_mutex_lock(&g_web_server.mutex);

    if (g_web_server.running) {
        pthread_mutex_unlock(&g_web_server.mutex);
        return DTU_OK;
    }

    /* 创建服务器套接字 */
    g_web_server.server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (g_web_server.server_socket < 0) {
        pthread_mutex_unlock(&g_web_server.mutex);
        DTU_LOG_ERROR("Failed to create server socket");
        return DTU_ERROR_NETWORK;
    }

    /* 设置套接字选项 */
    int opt = 1;
    if (setsockopt(g_web_server.server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
        close(g_web_server.server_socket);
        g_web_server.server_socket = -1;
        pthread_mutex_unlock(&g_web_server.mutex);
        DTU_LOG_ERROR("Failed to set socket options");
        return DTU_ERROR_NETWORK;
    }

    /* 绑定地址和端口 */
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(g_web_server.config.port);
    
    if (strcmp(g_web_server.config.bind_address, "0.0.0.0") == 0) {
        server_addr.sin_addr.s_addr = INADDR_ANY;
    } else {
        if (inet_pton(AF_INET, g_web_server.config.bind_address, &server_addr.sin_addr) <= 0) {
            close(g_web_server.server_socket);
            g_web_server.server_socket = -1;
            pthread_mutex_unlock(&g_web_server.mutex);
            DTU_LOG_ERROR("Invalid bind address: %s", g_web_server.config.bind_address);
            return DTU_ERROR_INVALID_PARAM;
        }
    }

    if (bind(g_web_server.server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        close(g_web_server.server_socket);
        g_web_server.server_socket = -1;
        pthread_mutex_unlock(&g_web_server.mutex);
        DTU_LOG_ERROR("Failed to bind to port %d", g_web_server.config.port);
        return DTU_ERROR_NETWORK;
    }

    /* 开始监听 */
    if (listen(g_web_server.server_socket, g_web_server.config.max_connections) < 0) {
        close(g_web_server.server_socket);
        g_web_server.server_socket = -1;
        pthread_mutex_unlock(&g_web_server.mutex);
        DTU_LOG_ERROR("Failed to listen on port %d", g_web_server.config.port);
        return DTU_ERROR_NETWORK;
    }

    g_web_server.running = true;

    /* 创建服务器线程 */
    if (pthread_create(&g_web_server.server_thread, NULL, web_server_thread, NULL) != 0) {
        close(g_web_server.server_socket);
        g_web_server.server_socket = -1;
        g_web_server.running = false;
        pthread_mutex_unlock(&g_web_server.mutex);
        DTU_LOG_ERROR("Failed to create server thread");
        return DTU_ERROR;
    }

    pthread_mutex_unlock(&g_web_server.mutex);

    DTU_LOG_INFO("Web server started on %s:%d", g_web_server.config.bind_address, g_web_server.config.port);
    return DTU_OK;
}

void dtu_web_stop(void)
{
    if (!g_web_server.initialized || !g_web_server.running) {
        return;
    }

    pthread_mutex_lock(&g_web_server.mutex);
    g_web_server.running = false;

    /* 关闭服务器套接字 */
    if (g_web_server.server_socket >= 0) {
        close(g_web_server.server_socket);
        g_web_server.server_socket = -1;
    }

    pthread_mutex_unlock(&g_web_server.mutex);

    /* 等待服务器线程结束 */
    pthread_join(g_web_server.server_thread, NULL);

    DTU_LOG_INFO("Web server stopped");
}

dtu_error_t dtu_web_register_handler(const char* path, http_method_t method, 
                                     http_handler_t handler, void* user_data)
{
    if (!g_web_server.initialized || !path || !handler) {
        return DTU_ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&g_web_server.mutex);

    /* 创建新路由项 */
    route_item_t* route = DTU_MALLOC(sizeof(route_item_t));
    if (!route) {
        pthread_mutex_unlock(&g_web_server.mutex);
        return DTU_ERROR_MEMORY;
    }

    memset(route, 0, sizeof(route_item_t));
    DTU_STRNCPY(route->path, path, sizeof(route->path));
    route->method = method;
    route->handler = handler;
    route->user_data = user_data;

    /* 添加到路由链表头部 */
    route->next = g_web_server.routes;
    g_web_server.routes = route;

    pthread_mutex_unlock(&g_web_server.mutex);

    DTU_LOG_DEBUG("Web handler registered: %s %s", http_method_strings[method], path);
    return DTU_OK;
}

void dtu_web_set_json_response(http_response_t* response, const char* json_str)
{
    if (!response || !json_str) {
        return;
    }

    dtu_web_set_content_type(response, "application/json");
    dtu_web_set_body(response, json_str, strlen(json_str));
    response->status = HTTP_STATUS_OK;
}

void dtu_web_set_error_response(http_response_t* response, http_status_t status, const char* message)
{
    if (!response) {
        return;
    }

    response->status = status;
    dtu_web_set_content_type(response, "application/json");
    
    char json_response[512];
    snprintf(json_response, sizeof(json_response), 
             "{\"error\":{\"code\":%d,\"message\":\"%s\"}}", 
             status, message ? message : dtu_web_status_string(status));
    
    dtu_web_set_body(response, json_response, strlen(json_response));
}

const char* dtu_web_status_string(http_status_t status)
{
    for (size_t i = 0; i < DTU_ARRAY_SIZE(http_status_descriptions); i++) {
        if (http_status_descriptions[i].code == status) {
            return http_status_descriptions[i].description;
        }
    }
    return "Unknown";
}

const char* dtu_web_method_string(http_method_t method)
{
    if (method >= 0 && method < DTU_ARRAY_SIZE(http_method_strings)) {
        return http_method_strings[method];
    }
    return "UNKNOWN";
}

/* 内部函数实现 */
static void* web_server_thread(void* arg)
{
    (void)arg;

    DTU_LOG_INFO("Web server thread started");

    while (g_web_server.running) {
        struct sockaddr_in client_addr;
        socklen_t client_len = sizeof(client_addr);

        /* 接受客户端连接 */
        int client_socket = accept(g_web_server.server_socket, 
                                  (struct sockaddr*)&client_addr, &client_len);
        
        if (client_socket < 0) {
            if (g_web_server.running) {
                DTU_LOG_ERROR("Failed to accept client connection");
            }
            continue;
        }

        /* 设置客户端套接字超时 */
        struct timeval timeout;
        timeout.tv_sec = g_web_server.config.timeout;
        timeout.tv_usec = 0;
        setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
        setsockopt(client_socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));

        /* 处理客户端请求 */
        handle_client_connection(client_socket);

        /* 关闭客户端连接 */
        close(client_socket);

        /* 更新请求计数 */
        pthread_mutex_lock(&g_web_server.mutex);
        g_web_server.request_count++;
        pthread_mutex_unlock(&g_web_server.mutex);
    }

    DTU_LOG_INFO("Web server thread stopped");
    return NULL;
}

static void handle_client_connection(int client_socket)
{
    char buffer[4096];
    ssize_t bytes_received = recv(client_socket, buffer, sizeof(buffer) - 1, 0);

    if (bytes_received <= 0) {
        return;
    }

    buffer[bytes_received] = '\0';

    /* 解析HTTP请求 */
    http_request_t request;
    if (parse_http_request(buffer, &request) != DTU_OK) {
        send_error_response(client_socket, HTTP_STATUS_BAD_REQUEST, "Invalid request");
        return;
    }

    /* 查找路由处理器 */
    route_item_t* route = NULL;
    if (find_route_handler(&request, &route) == DTU_OK && route) {
        /* 执行API处理器 */
        http_response_t response;
        memset(&response, 0, sizeof(response));

        if (route->handler(&request, &response, route->user_data) == DTU_OK) {
            send_http_response(client_socket, &response);
        } else {
            send_error_response(client_socket, HTTP_STATUS_INTERNAL_ERROR, "Handler error");
        }
    } else {
        /* 尝试提供静态文件 */
        char file_path[512];
        if (strcmp(request.uri, "/") == 0) {
            snprintf(file_path, sizeof(file_path), "%s/index.html", g_web_server.config.document_root);
        } else {
            snprintf(file_path, sizeof(file_path), "%s%s", g_web_server.config.document_root, request.uri);
        }

        send_static_file(client_socket, file_path);
    }
}

static dtu_error_t parse_http_request(const char* request_data, http_request_t* request)
{
    if (!request_data || !request) {
        return DTU_ERROR_INVALID_PARAM;
    }

    memset(request, 0, sizeof(http_request_t));

    /* 解析请求行 */
    char method_str[16];
    char uri[256];
    char version[16];

    if (sscanf(request_data, "%15s %255s %15s", method_str, uri, version) != 3) {
        return DTU_ERROR_INVALID_PARAM;
    }

    /* 解析HTTP方法 */
    request->method = dtu_web_method_from_string(method_str);
    DTU_STRNCPY(request->uri, uri, sizeof(request->uri));

    /* 分离URI和查询字符串 */
    char* query_start = strchr(request->uri, '?');
    if (query_start) {
        *query_start = '\0';
        DTU_STRNCPY(request->query_string, query_start + 1, sizeof(request->query_string));
    }

    /* 解析请求头 */
    const char* header_start = strstr(request_data, "\r\n");
    if (header_start) {
        header_start += 2;
        const char* body_start = strstr(header_start, "\r\n\r\n");

        if (body_start) {
            size_t header_len = body_start - header_start;
            if (header_len < sizeof(request->headers)) {
                memcpy(request->headers, header_start, header_len);
                request->headers[header_len] = '\0';
            }

            /* 解析请求体 */
            body_start += 4;
            size_t body_len = strlen(body_start);
            if (body_len < sizeof(request->body)) {
                memcpy(request->body, body_start, body_len);
                request->body[body_len] = '\0';
                request->body_length = body_len;
            }
        }
    }

    return DTU_OK;
}

static dtu_error_t find_route_handler(const http_request_t* request, route_item_t** route)
{
    if (!request || !route) {
        return DTU_ERROR_INVALID_PARAM;
    }

    *route = NULL;

    pthread_mutex_lock(&g_web_server.mutex);

    route_item_t* current = g_web_server.routes;
    while (current) {
        if (current->method == request->method && strcmp(current->path, request->uri) == 0) {
            *route = current;
            pthread_mutex_unlock(&g_web_server.mutex);
            return DTU_OK;
        }
        current = current->next;
    }

    pthread_mutex_unlock(&g_web_server.mutex);
    return DTU_ERROR_NOT_FOUND;
}

static void send_http_response(int client_socket, const http_response_t* response)
{
    if (!response) {
        return;
    }

    char response_buffer[8192];
    int len = snprintf(response_buffer, sizeof(response_buffer),
                      "HTTP/1.1 %d %s\r\n"
                      "Content-Type: %s\r\n"
                      "Content-Length: %zu\r\n"
                      "Connection: close\r\n"
                      "%s"
                      "\r\n",
                      response->status,
                      dtu_web_status_string(response->status),
                      response->content_type[0] ? response->content_type : "text/plain",
                      response->body_length,
                      response->headers);

    if (len > 0 && len < (int)sizeof(response_buffer)) {
        send(client_socket, response_buffer, len, 0);
        if (response->body_length > 0) {
            send(client_socket, response->body, response->body_length, 0);
        }
    }
}

static void send_static_file(int client_socket, const char* file_path)
{
    FILE* file = fopen(file_path, "rb");
    if (!file) {
        send_error_response(client_socket, HTTP_STATUS_NOT_FOUND, "File not found");
        return;
    }

    /* 获取文件大小 */
    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);

    if (file_size <= 0 || file_size > 1024 * 1024) { /* 限制1MB */
        fclose(file);
        send_error_response(client_socket, HTTP_STATUS_INTERNAL_ERROR, "File too large");
        return;
    }

    /* 确定内容类型 */
    const char* content_type = "text/plain";
    const char* ext = strrchr(file_path, '.');
    if (ext) {
        if (strcmp(ext, ".html") == 0 || strcmp(ext, ".htm") == 0) {
            content_type = "text/html";
        } else if (strcmp(ext, ".css") == 0) {
            content_type = "text/css";
        } else if (strcmp(ext, ".js") == 0) {
            content_type = "application/javascript";
        } else if (strcmp(ext, ".json") == 0) {
            content_type = "application/json";
        } else if (strcmp(ext, ".png") == 0) {
            content_type = "image/png";
        } else if (strcmp(ext, ".jpg") == 0 || strcmp(ext, ".jpeg") == 0) {
            content_type = "image/jpeg";
        }
    }

    /* 发送响应头 */
    char response_header[512];
    int header_len = snprintf(response_header, sizeof(response_header),
                             "HTTP/1.1 200 OK\r\n"
                             "Content-Type: %s\r\n"
                             "Content-Length: %ld\r\n"
                             "Connection: close\r\n"
                             "\r\n",
                             content_type, file_size);

    send(client_socket, response_header, header_len, 0);

    /* 发送文件内容 */
    char buffer[4096];
    size_t bytes_read;
    while ((bytes_read = fread(buffer, 1, sizeof(buffer), file)) > 0) {
        send(client_socket, buffer, bytes_read, 0);
    }

    fclose(file);
}

static void send_error_response(int client_socket, http_status_t status, const char* message)
{
    char response[1024];
    int len = snprintf(response, sizeof(response),
                      "HTTP/1.1 %d %s\r\n"
                      "Content-Type: application/json\r\n"
                      "Connection: close\r\n"
                      "\r\n"
                      "{\"error\":{\"code\":%d,\"message\":\"%s\"}}",
                      status, dtu_web_status_string(status),
                      status, message ? message : dtu_web_status_string(status));

    if (len > 0 && len < (int)sizeof(response)) {
        send(client_socket, response, len, 0);
    }
}

http_method_t dtu_web_method_from_string(const char* str)
{
    if (!str) return HTTP_METHOD_GET;

    for (size_t i = 0; i < DTU_ARRAY_SIZE(http_method_strings); i++) {
        if (strcasecmp(str, http_method_strings[i]) == 0) {
            return (http_method_t)i;
        }
    }
    return HTTP_METHOD_GET;
}

void dtu_web_set_status(http_response_t* response, http_status_t status)
{
    if (response) {
        response->status = status;
    }
}

void dtu_web_set_header(http_response_t* response, const char* name, const char* value)
{
    if (!response || !name || !value) {
        return;
    }

    char header_line[256];
    snprintf(header_line, sizeof(header_line), "%s: %s\r\n", name, value);

    size_t current_len = strlen(response->headers);
    size_t header_len = strlen(header_line);

    if (current_len + header_len < sizeof(response->headers) - 1) {
        strcat(response->headers, header_line);
    }
}

void dtu_web_set_content_type(http_response_t* response, const char* content_type)
{
    if (response && content_type) {
        DTU_STRNCPY(response->content_type, content_type, sizeof(response->content_type));
    }
}

void dtu_web_set_body(http_response_t* response, const char* body, size_t length)
{
    if (!response || !body) {
        return;
    }

    size_t copy_len = DTU_MIN(length, sizeof(response->body) - 1);
    memcpy(response->body, body, copy_len);
    response->body[copy_len] = '\0';
    response->body_length = copy_len;
}

static void free_routes(void)
{
    route_item_t* route = g_web_server.routes;
    while (route) {
        route_item_t* next = route->next;
        DTU_FREE(route);
        route = next;
    }
    g_web_server.routes = NULL;
}

static void free_sessions(void)
{
    session_t* session = g_web_server.sessions;
    while (session) {
        session_t* next = session->next;
        DTU_FREE(session);
        session = next;
    }
    g_web_server.sessions = NULL;
}

/* API处理器实现 */
static dtu_error_t api_status_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)request;
    (void)user_data;

    extern system_status_t g_system_status;
    extern device_info_t g_device_info;

    char json_response[2048];
    snprintf(json_response, sizeof(json_response),
             "{"
             "\"device\":{"
             "\"id\":\"%s\","
             "\"model\":%d,"
             "\"firmware\":\"%s\","
             "\"hardware\":\"%s\""
             "},"
             "\"system\":{"
             "\"running\":%s,"
             "\"uptime\":%ld,"
             "\"data_sent\":%u,"
             "\"data_received\":%u,"
             "\"error_count\":%u"
             "},"
             "\"network\":{"
             "\"ethernet\":\"%s\","
             "\"wifi\":\"%s\","
             "\"lte\":\"%s\""
             "}"
             "}",
             g_device_info.device_id,
             g_device_info.model,
             g_device_info.firmware_version,
             g_device_info.hardware_version,
             g_system_status.system_running ? "true" : "false",
             g_system_status.uptime,
             g_system_status.data_sent,
             g_system_status.data_received,
             g_system_status.error_count,
             dtu_network_status_string(g_system_status.network_status[0]),
             dtu_network_status_string(g_system_status.network_status[1]),
             dtu_network_status_string(g_system_status.network_status[2]));

    dtu_web_set_json_response(response, json_response);
    return DTU_OK;
}

static dtu_error_t api_config_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method == HTTP_METHOD_GET) {
        /* 返回当前配置 */
        const dtu_config_t* config = dtu_config_get();
        if (!config) {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
            return DTU_ERROR;
        }

        char json_response[4096];
        snprintf(json_response, sizeof(json_response),
                 "{"
                 "\"serial\":{"
                 "\"rs485_baudrate\":%d,"
                 "\"rs485_databits\":%d,"
                 "\"rs485_stopbits\":%d,"
                 "\"rs485_parity\":\"%c\""
                 "},"
                 "\"network\":{"
                 "\"dhcp_enable\":%s,"
                 "\"ip\":\"%s\","
                 "\"netmask\":\"%s\","
                 "\"gateway\":\"%s\""
                 "},"
                 "\"collect\":{"
                 "\"interval\":%d,"
                 "\"auto_collect\":%s,"
                 "\"retry_count\":%d"
                 "}"
                 "}",
                 config->rs485_config.baudrate,
                 config->rs485_config.databits,
                 config->rs485_config.stopbits,
                 config->rs485_config.parity,
                 config->ethernet_config.dhcp_enable ? "true" : "false",
                 config->ethernet_config.ip,
                 config->ethernet_config.netmask,
                 config->ethernet_config.gateway,
                 config->collect_config.interval,
                 config->collect_config.auto_collect ? "true" : "false",
                 config->collect_config.retry_count);

        dtu_web_set_json_response(response, json_response);
        return DTU_OK;
    } else if (request->method == HTTP_METHOD_POST) {
        /* 更新配置 */
        /* TODO: 解析JSON请求体并更新配置 */
        dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"Configuration updated\"}");
        return DTU_OK;
    }

    dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
    return DTU_ERROR;
}

static dtu_error_t api_network_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method == HTTP_METHOD_GET) {
        /* 获取网络配置信息 */
        const dtu_config_t* config = dtu_config_get();
        if (!config) {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
            return DTU_ERROR;
        }

        /* 获取网络接口状态信息 */
        network_interface_t interfaces[3];
        int count = dtu_network_get_all_interfaces(interfaces, 3);

        char json_response[4096];
        int len = snprintf(json_response, sizeof(json_response),
                          "{"
                          "\"device_model\":%d,"
                          "\"ethernet_config\":{"
                          "\"dhcp_enable\":%s,"
                          "\"ip\":\"%s\","
                          "\"netmask\":\"%s\","
                          "\"gateway\":\"%s\","
                          "\"dns1\":\"%s\","
                          "\"dns2\":\"%s\""
                          "}",
                          config->device_info.model,
                          config->ethernet_config.dhcp_enable ? "true" : "false",
                          config->ethernet_config.ip,
                          config->ethernet_config.netmask,
                          config->ethernet_config.gateway,
                          config->ethernet_config.dns1,
                          config->ethernet_config.dns2);

        /* 根据设备型号添加WiFi配置 */
        if (config->device_info.model == DTU_MODEL_WIFI_ETHERNET) {
            len += snprintf(json_response + len, sizeof(json_response) - len,
                           ",\"wifi_config\":{"
                           "\"ssid\":\"%s\","
                           "\"password\":\"%s\","
                           "\"security\":%d"
                           "}",
                           config->wifi_config.ssid,
                           config->wifi_config.password,
                           config->wifi_config.security_type);
        }

        /* 根据设备型号添加4G配置 */
        if (config->device_info.model == DTU_MODEL_4G_ETHERNET) {
            len += snprintf(json_response + len, sizeof(json_response) - len,
                           ",\"lte_config\":{"
                           "\"apn\":\"%s\","
                           "\"username\":\"%s\","
                           "\"password\":\"%s\","
                           "\"pin\":\"%d\""
                           "}",
                           config->lte_config.apn,
                           config->lte_config.username,
                           config->lte_config.password,
                           config->lte_config.pin_code);
        }

        /* 添加网络接口状态信息 */
        len += snprintf(json_response + len, sizeof(json_response) - len, ",\"interfaces\":[");

        for (int i = 0; i < count && len < (int)sizeof(json_response) - 200; i++) {
            len += snprintf(json_response + len, sizeof(json_response) - len,
                           "%s{"
                           "\"type\":\"%s\","
                           "\"status\":\"%s\","
                           "\"ip\":\"%s\","
                           "\"signal_strength\":%d,"
                           "\"bytes_sent\":%llu,"
                           "\"bytes_received\":%llu"
                           "}",
                           i > 0 ? "," : "",
                           dtu_network_type_string(interfaces[i].type),
                           dtu_network_status_string(interfaces[i].status),
                           interfaces[i].ip_address,
                           interfaces[i].signal_strength,
                           (unsigned long long)interfaces[i].bytes_sent,
                           (unsigned long long)interfaces[i].bytes_received);
        }

        if (len < (int)sizeof(json_response) - 10) {
            strcat(json_response, "]}");
        }

        dtu_web_set_json_response(response, json_response);
        return DTU_OK;

    } else if (request->method == HTTP_METHOD_POST) {
        /* 更新网络配置 */
        if (request->body_length == 0 || request->body[0] == '\0') {
            dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing request body");
            return DTU_ERROR;
        }

        dtu_config_t* config = (dtu_config_t*)dtu_config_get();
        if (!config) {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
            return DTU_ERROR;
        }

        bool config_changed = false;
        dtu_error_t result = DTU_OK;

        /* 处理以太网配置 */
        char* ethernet_config_str = get_json_string_value(request->body, "ethernet_config");
        if (ethernet_config_str) {
            bool dhcp_enable = get_json_bool_value(ethernet_config_str, "dhcp_enable", config->ethernet_config.dhcp_enable);
            char* ip = get_json_string_value(ethernet_config_str, "ip");
            char* netmask = get_json_string_value(ethernet_config_str, "netmask");
            char* gateway = get_json_string_value(ethernet_config_str, "gateway");
            char* dns1 = get_json_string_value(ethernet_config_str, "dns1");
            char* dns2 = get_json_string_value(ethernet_config_str, "dns2");

            /* 更新以太网配置 */
            config->ethernet_config.dhcp_enable = dhcp_enable;
            if (ip && strlen(ip) > 0) {
                DTU_STRNCPY(config->ethernet_config.ip, ip, sizeof(config->ethernet_config.ip));
            }
            if (netmask && strlen(netmask) > 0) {
                DTU_STRNCPY(config->ethernet_config.netmask, netmask, sizeof(config->ethernet_config.netmask));
            }
            if (gateway && strlen(gateway) > 0) {
                DTU_STRNCPY(config->ethernet_config.gateway, gateway, sizeof(config->ethernet_config.gateway));
            }
            if (dns1 && strlen(dns1) > 0) {
                DTU_STRNCPY(config->ethernet_config.dns1, dns1, sizeof(config->ethernet_config.dns1));
            }
            if (dns2 && strlen(dns2) > 0) {
                DTU_STRNCPY(config->ethernet_config.dns2, dns2, sizeof(config->ethernet_config.dns2));
            }

            /* 应用以太网配置 */
            if (dtu_network_config_ethernet(&config->ethernet_config) == DTU_OK) {
                DTU_LOG_INFO("Ethernet configuration applied successfully");
                config_changed = true;
            } else {
                DTU_LOG_ERROR("Failed to apply ethernet configuration");
                result = DTU_ERROR;
            }

            /* 释放内存 */
            if (ip) DTU_FREE(ip);
            if (netmask) DTU_FREE(netmask);
            if (gateway) DTU_FREE(gateway);
            if (dns1) DTU_FREE(dns1);
            if (dns2) DTU_FREE(dns2);
            DTU_FREE(ethernet_config_str);
        }

        /* 处理WiFi配置（仅WiFi+Ethernet版本支持） */
        if (config->device_info.model == DTU_MODEL_WIFI_ETHERNET) {
            char* wifi_config_str = get_json_string_value(request->body, "wifi_config");
            if (wifi_config_str) {
                char* ssid = get_json_string_value(wifi_config_str, "ssid");
                char* password = get_json_string_value(wifi_config_str, "password");
                int security = get_json_int_value(wifi_config_str, "security", config->wifi_config.security_type);

                /* 更新WiFi配置 */
                if (ssid && strlen(ssid) > 0) {
                    DTU_STRNCPY(config->wifi_config.ssid, ssid, sizeof(config->wifi_config.ssid));
                }
                if (password && strlen(password) > 0) {
                    DTU_STRNCPY(config->wifi_config.password, password, sizeof(config->wifi_config.password));
                }
                config->wifi_config.security_type = security;

                /* 应用WiFi配置 */
                if (dtu_network_config_wifi(&config->ethernet_config, &config->wifi_config) == DTU_OK) {
                    DTU_LOG_INFO("WiFi configuration applied successfully");
                    config_changed = true;
                } else {
                    DTU_LOG_ERROR("Failed to apply WiFi configuration");
                    result = DTU_ERROR;
                }

                /* 释放内存 */
                if (ssid) DTU_FREE(ssid);
                if (password) DTU_FREE(password);
                DTU_FREE(wifi_config_str);
            }
        }

        /* 处理4G配置（仅4G+Ethernet版本支持） */
        if (config->device_info.model == DTU_MODEL_4G_ETHERNET) {
            char* lte_config_str = get_json_string_value(request->body, "lte_config");
            if (lte_config_str) {
                char* apn = get_json_string_value(lte_config_str, "apn");
                char* username = get_json_string_value(lte_config_str, "username");
                char* password = get_json_string_value(lte_config_str, "password");
                int pin = get_json_int_value(lte_config_str, "pin", config->lte_config.pin_code);

                /* 更新4G配置 */
                if (apn && strlen(apn) > 0) {
                    DTU_STRNCPY(config->lte_config.apn, apn, sizeof(config->lte_config.apn));
                }
                if (username && strlen(username) > 0) {
                    DTU_STRNCPY(config->lte_config.username, username, sizeof(config->lte_config.username));
                }
                if (password && strlen(password) > 0) {
                    DTU_STRNCPY(config->lte_config.password, password, sizeof(config->lte_config.password));
                }
                config->lte_config.pin_code = pin;

                /* 应用4G配置 */
                if (dtu_network_config_lte(&config->ethernet_config, &config->lte_config) == DTU_OK) {
                    DTU_LOG_INFO("4G configuration applied successfully");
                    config_changed = true;
                } else {
                    DTU_LOG_ERROR("Failed to apply 4G configuration");
                    result = DTU_ERROR;
                }

                /* 释放内存 */
                if (apn) DTU_FREE(apn);
                if (username) DTU_FREE(username);
                if (password) DTU_FREE(password);
                DTU_FREE(lte_config_str);
            }
        }

        /* 保存配置 */
        if (config_changed) {
            dtu_config_save();
        }

        if (result == DTU_OK) {
            dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"Network configuration updated\"}");
        } else {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to apply network configuration");
        }
        return result;
    }

    dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
    return DTU_ERROR;
}

static dtu_error_t api_login_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method != HTTP_METHOD_POST) {
        dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
        return DTU_ERROR;
    }

    /* TODO: 解析JSON请求体获取用户名和密码 */
    /* 这里简化处理，假设用户名密码正确 */

    if (dtu_web_authenticate("admin", "admin123")) {
        char* session_id = generate_session_id();
        if (session_id) {
            char json_response[256];
            snprintf(json_response, sizeof(json_response),
                     "{\"result\":\"success\",\"session_id\":\"%s\"}", session_id);
            dtu_web_set_json_response(response, json_response);
            DTU_FREE(session_id);
            return DTU_OK;
        }
    }

    dtu_web_set_error_response(response, HTTP_STATUS_UNAUTHORIZED, "Invalid credentials");
    return DTU_ERROR;
}

static dtu_error_t api_logout_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)request;
    (void)user_data;

    /* TODO: 销毁会话 */
    dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"Logged out\"}");
    return DTU_OK;
}

bool dtu_web_authenticate(const char* username, const char* password)
{
    if (!username || !password) {
        return false;
    }

    return (strcmp(username, g_web_server.config.username) == 0 &&
            strcmp(password, g_web_server.config.password) == 0);
}

static char* generate_session_id(void)
{
    char* session_id = DTU_MALLOC(64);
    if (!session_id) {
        return NULL;
    }

    /* 生成简单的会话ID */
    snprintf(session_id, 64, "sess_%ld_%d", time(NULL), rand());
    return session_id;
}

/* 辅助函数实现 */
static char* get_json_string_value(const char* json, const char* key)
{
    if (!json || !key) return NULL;

    char search_key[128];
    snprintf(search_key, sizeof(search_key), "\"%s\":", key);

    char* pos = strstr(json, search_key);
    if (!pos) return NULL;

    /* 跳过键名，找到冒号后的值 */
    pos += strlen(search_key);

    /* 跳过空格 */
    while (*pos == ' ' || *pos == '\t') pos++;

    /* 检查是否是字符串值（以引号开始） */
    if (*pos != '"') return NULL;
    pos++; /* 跳过开始引号 */

    /* 找到结束引号 */
    char* end = strchr(pos, '"');
    if (!end) return NULL;

    /* 分配内存并复制字符串 */
    int len = end - pos;
    char* result = DTU_MALLOC(len + 1);
    if (result) {
        strncpy(result, pos, len);
        result[len] = '\0';
    }
    return result;
}

static int get_json_int_value(const char* json, const char* key, int default_value)
{
    if (!json || !key) return default_value;

    char search_key[128];
    snprintf(search_key, sizeof(search_key), "\"%s\":", key);

    char* pos = strstr(json, search_key);
    if (!pos) return default_value;

    pos = strchr(pos, ':');
    if (!pos) return default_value;

    return atoi(pos + 1);
}

static bool get_json_bool_value(const char* json, const char* key, bool default_value)
{
    if (!json || !key) return default_value;

    char search_key[128];
    snprintf(search_key, sizeof(search_key), "\"%s\":", key);

    char* pos = strstr(json, search_key);
    if (!pos) return default_value;

    pos = strchr(pos, ':');
    if (!pos) return default_value;

    return (strstr(pos, "true") != NULL);
}

/* 串口配置API处理函数 */
static dtu_error_t api_serial_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method == HTTP_METHOD_GET) {
        /* 返回串口配置 */
        const dtu_config_t* config = dtu_config_get();
        if (!config) {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
            return DTU_ERROR;
        }

        char json_response[2048];
        snprintf(json_response, sizeof(json_response),
                 "{"
                 "\"rs485\":{"
                 "\"device\":\"%s\","
                 "\"baudrate\":%d,"
                 "\"databits\":%d,"
                 "\"stopbits\":%d,"
                 "\"parity\":\"%c\","
                 "\"timeout\":%d"
                 "},"
                 "\"rs232\":{"
                 "\"device\":\"%s\","
                 "\"baudrate\":%d,"
                 "\"databits\":%d,"
                 "\"stopbits\":%d,"
                 "\"parity\":\"%c\","
                 "\"timeout\":%d"
                 "}"
                 "}",
                 config->rs485_config.device,
                 config->rs485_config.baudrate,
                 config->rs485_config.databits,
                 config->rs485_config.stopbits,
                 config->rs485_config.parity,
                 config->rs485_config.timeout,
                 config->rs232_config.device,
                 config->rs232_config.baudrate,
                 config->rs232_config.databits,
                 config->rs232_config.stopbits,
                 config->rs232_config.parity,
                 config->rs232_config.timeout);

        dtu_web_set_json_response(response, json_response);
        return DTU_OK;

    } else if (request->method == HTTP_METHOD_POST) {
        /* 更新串口配置 */
        if (request->body_length == 0 || request->body[0] == '\0') {
            dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing request body");
            return DTU_ERROR;
        }

        /* 解析JSON请求 */
        char* rs485_device = get_json_string_value(request->body, "rs485_device");
        int rs485_baudrate = get_json_int_value(request->body, "rs485_baudrate", 9600);
        int rs485_databits = get_json_int_value(request->body, "rs485_databits", 8);
        int rs485_stopbits = get_json_int_value(request->body, "rs485_stopbits", 1);
        char* rs485_parity_str = get_json_string_value(request->body, "rs485_parity");
        int rs485_timeout = get_json_int_value(request->body, "rs485_timeout", 1000);

        char* rs232_device = get_json_string_value(request->body, "rs232_device");
        int rs232_baudrate = get_json_int_value(request->body, "rs232_baudrate", 9600);
        int rs232_databits = get_json_int_value(request->body, "rs232_databits", 8);
        int rs232_stopbits = get_json_int_value(request->body, "rs232_stopbits", 1);
        char* rs232_parity_str = get_json_string_value(request->body, "rs232_parity");
        int rs232_timeout = get_json_int_value(request->body, "rs232_timeout", 1000);

        /* 更新配置 */
        dtu_config_t* config = (dtu_config_t*)dtu_config_get();
        if (config) {
            if (rs485_device) {
                DTU_STRNCPY(config->rs485_config.device, rs485_device, sizeof(config->rs485_config.device));
                DTU_FREE(rs485_device);
            }
            config->rs485_config.baudrate = rs485_baudrate;
            config->rs485_config.databits = rs485_databits;
            config->rs485_config.stopbits = rs485_stopbits;
            if (rs485_parity_str) {
                config->rs485_config.parity = rs485_parity_str[0];
                DTU_FREE(rs485_parity_str);
            }
            config->rs485_config.timeout = rs485_timeout;

            if (rs232_device) {
                DTU_STRNCPY(config->rs232_config.device, rs232_device, sizeof(config->rs232_config.device));
                DTU_FREE(rs232_device);
            }
            config->rs232_config.baudrate = rs232_baudrate;
            config->rs232_config.databits = rs232_databits;
            config->rs232_config.stopbits = rs232_stopbits;
            if (rs232_parity_str) {
                config->rs232_config.parity = rs232_parity_str[0];
                DTU_FREE(rs232_parity_str);
            }
            config->rs232_config.timeout = rs232_timeout;

            /* 保存配置 */
            dtu_config_save();
        }

        dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"Serial configuration updated\"}");
        return DTU_OK;
    }

    dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
    return DTU_ERROR;
}

/* 数据采集配置API处理函数 */
static dtu_error_t api_collect_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method == HTTP_METHOD_GET) {
        /* 返回采集配置 */
        const dtu_config_t* config = dtu_config_get();
        if (!config) {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
            return DTU_ERROR;
        }

        char json_response[4096];
        int pos = 0;
        int remaining = sizeof(json_response) - 1;

        /* 构建包含设备信息的响应 */
        pos += snprintf(json_response + pos, remaining - pos,
                       "{"
                       "\"interval\":%d,"
                       "\"auto_collect\":%s,"
                       "\"retry_count\":%d,"
                       "\"retry_interval\":%d,"
                       "\"devices\":[",
                       config->collect_config.interval,
                       config->collect_config.auto_collect ? "true" : "false",
                       config->collect_config.retry_count,
                       config->collect_config.retry_interval);

        /* 添加Modbus设备信息 */
        for (int i = 0; i < config->modbus_config.device_count && i < 16; i++) {
            pos += snprintf(json_response + pos, remaining - pos,
                           "%s{"
                           "\"id\":%d,"
                           "\"name\":\"%s\","
                           "\"enabled\":%s,"
                           "\"crc_enable\":%s,"
                           "\"poll_string\":\"%s\","
                           "\"serial_port\":\"%s\","
                           "\"description\":\"%s\""
                           "}",
                           (i > 0) ? "," : "",
                           config->modbus_config.devices[i].id,
                           config->modbus_config.devices[i].name,
                           config->modbus_config.devices[i].enabled ? "true" : "false",
                           config->modbus_config.devices[i].crc_enable ? "true" : "false",
                           config->modbus_config.devices[i].poll_string,
                           config->modbus_config.devices[i].serial_port,
                           config->modbus_config.devices[i].description);
        }

        pos += snprintf(json_response + pos, remaining - pos, "]}");

        dtu_web_set_json_response(response, json_response);
        return DTU_OK;

    } else if (request->method == HTTP_METHOD_POST) {
        /* 更新采集配置 */
        if (request->body_length == 0 || request->body[0] == '\0') {
            dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing request body");
            return DTU_ERROR;
        }

        /* 解析采集配置 */
        int interval = get_json_int_value(request->body, "interval", 30);
        bool auto_collect = get_json_bool_value(request->body, "auto_collect", true);
        int retry_count = get_json_int_value(request->body, "retry_count", 3);
        int retry_interval = get_json_int_value(request->body, "retry_interval", 5);

        /* 更新配置 */
        dtu_config_t* config = (dtu_config_t*)dtu_config_get();
        if (config) {
            bool old_auto_collect = config->collect_config.auto_collect;

            config->collect_config.interval = interval;
            config->collect_config.auto_collect = auto_collect;
            config->collect_config.retry_count = retry_count;
            config->collect_config.retry_interval = retry_interval;

            /* 保存配置 */
            dtu_config_save();

            /* 如果自动采集开关状态发生变化，实时启动或停止采集任务 */
            if (old_auto_collect != auto_collect) {
                if (auto_collect) {
                    DTU_LOG_INFO("Auto collect enabled, starting data collection");
                    dtu_error_t start_result = dtu_data_collect_start();
                    if (start_result != DTU_OK) {
                        DTU_LOG_ERROR("Failed to start data collection");
                    }
                } else {
                    DTU_LOG_INFO("Auto collect disabled, stopping data collection");
                    dtu_error_t stop_result = dtu_data_collect_stop();
                    if (stop_result != DTU_OK) {
                        DTU_LOG_ERROR("Failed to stop data collection");
                    }
                }
            }
        }

        dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"Collect configuration updated and applied\"}");
        return DTU_OK;
    }

    dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
    return DTU_ERROR;
}

/* 开始采集API处理函数 */
static dtu_error_t api_collect_start_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method != HTTP_METHOD_POST) {
        dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
        return DTU_ERROR;
    }

    DTU_LOG_INFO("Starting data collection via API");

    /* 启动数据采集 */
    dtu_error_t result = dtu_data_collect_start();
    DTU_LOG_INFO("dtu_data_collect_start() returned: %d", result);
    if (result == DTU_OK) {
        /* 更新配置中的自动采集状态 */
        dtu_config_t* config = (dtu_config_t*)dtu_config_get();
        if (config) {
            config->collect_config.auto_collect = true;
            dtu_config_save();
        }

        dtu_web_set_json_response(response, "{\"success\":true,\"message\":\"Data collection started\"}");
        DTU_LOG_INFO("Data collection started successfully");
    } else {
        dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to start data collection");
        DTU_LOG_ERROR("Failed to start data collection");
    }

    return result;
}

/* 停止采集API处理函数 */
static dtu_error_t api_collect_stop_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method != HTTP_METHOD_POST) {
        dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
        return DTU_ERROR;
    }

    DTU_LOG_INFO("Stopping data collection via API");

    /* 停止数据采集 */
    dtu_error_t result = dtu_data_collect_stop();
    DTU_LOG_INFO("dtu_data_collect_stop() returned: %d", result);
    if (result == DTU_OK) {
        /* 更新配置中的自动采集状态 */
        dtu_config_t* config = (dtu_config_t*)dtu_config_get();
        if (config) {
            config->collect_config.auto_collect = false;
            dtu_config_save();
        }

        dtu_web_set_json_response(response, "{\"success\":true,\"message\":\"Data collection stopped\"}");
        DTU_LOG_INFO("Data collection stopped successfully");
    } else {
        dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to stop data collection");
        DTU_LOG_ERROR("Failed to stop data collection");
    }

    return result;
}

/* 数据推送配置API处理函数 */
static dtu_error_t api_push_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method == HTTP_METHOD_GET) {
        /* 返回推送配置 */
        const dtu_config_t* config = dtu_config_get();
        if (!config) {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
            return DTU_ERROR;
        }

        char json_response[2048];
        snprintf(json_response, sizeof(json_response),
                 "{"
                 "\"protocol\":%d,"
                 "\"format\":%d,"
                 "\"server_host\":\"%s\","
                 "\"server_port\":%d,"
                 "\"username\":\"%s\","
                 "\"password\":\"%s\","
                 "\"topic\":\"%s\","
                 "\"client_id\":\"%s\","
                 "\"timeout\":%d,"
                 "\"retry_count\":%d,"
                 "\"retry_interval\":%d,"
                 "\"enable_ssl\":%s,"
                 "\"enable_compression\":%s,"
                 "\"keepalive\":%d,"
                 "\"clean_session\":%s"
                 "}",
                 config->push_config.protocol,
                 config->push_config.format,
                 config->push_config.server_host,
                 config->push_config.server_port,
                 config->push_config.username,
                 config->push_config.password,
                 config->push_config.topic,
                 config->push_config.client_id,
                 config->push_config.timeout,
                 config->push_config.retry_count,
                 config->push_config.retry_interval,
                 config->push_config.enable_ssl ? "true" : "false",
                 config->push_config.enable_compression ? "true" : "false",
                 config->push_config.keepalive,
                 config->push_config.clean_session ? "true" : "false");

        dtu_web_set_json_response(response, json_response);
        return DTU_OK;

    } else if (request->method == HTTP_METHOD_POST) {
        /* 更新推送配置 */
        if (request->body_length == 0 || request->body[0] == '\0') {
            dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing request body");
            return DTU_ERROR;
        }

        /* 解析推送配置 */
        int protocol = get_json_int_value(request->body, "protocol", 0);
        int format = get_json_int_value(request->body, "format", 0);
        char* server_host = get_json_string_value(request->body, "server_host");
        int server_port = get_json_int_value(request->body, "server_port", 1883);
        char* username = get_json_string_value(request->body, "username");
        char* password = get_json_string_value(request->body, "password");
        char* topic = get_json_string_value(request->body, "topic");
        char* client_id = get_json_string_value(request->body, "client_id");
        int timeout = get_json_int_value(request->body, "timeout", 30);
        int retry_count = get_json_int_value(request->body, "retry_count", 3);
        int retry_interval = get_json_int_value(request->body, "retry_interval", 5);
        bool enable_ssl = get_json_bool_value(request->body, "enable_ssl", false);
        bool enable_compression = get_json_bool_value(request->body, "enable_compression", false);
        int keepalive = get_json_int_value(request->body, "keepalive", 60);
        bool clean_session = get_json_bool_value(request->body, "clean_session", true);

        /* 更新配置 */
        dtu_config_t* config = (dtu_config_t*)dtu_config_get();
        if (config) {
            config->push_config.protocol = protocol;
            config->push_config.format = format;
            if (server_host) {
                DTU_STRNCPY(config->push_config.server_host, server_host, sizeof(config->push_config.server_host));
                DTU_FREE(server_host);
            }
            config->push_config.server_port = server_port;
            if (username) {
                DTU_STRNCPY(config->push_config.username, username, sizeof(config->push_config.username));
                DTU_FREE(username);
            }
            if (password) {
                DTU_STRNCPY(config->push_config.password, password, sizeof(config->push_config.password));
                DTU_FREE(password);
            }
            if (topic) {
                DTU_STRNCPY(config->push_config.topic, topic, sizeof(config->push_config.topic));
                DTU_FREE(topic);
            }
            if (client_id) {
                DTU_STRNCPY(config->push_config.client_id, client_id, sizeof(config->push_config.client_id));
                DTU_FREE(client_id);
            }
            config->push_config.timeout = timeout;
            config->push_config.retry_count = retry_count;
            config->push_config.retry_interval = retry_interval;
            config->push_config.enable_ssl = enable_ssl;
            config->push_config.enable_compression = enable_compression;
            config->push_config.keepalive = keepalive;
            config->push_config.clean_session = clean_session;

            /* 保存配置 */
            dtu_config_save();
        }

        dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"Push configuration updated\"}");
        return DTU_OK;
    }

    dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
    return DTU_ERROR;
}

/* 系统设置API处理函数 */
static dtu_error_t api_system_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method == HTTP_METHOD_GET) {
        /* 返回系统设置 */
        const dtu_config_t* config = dtu_config_get();
        if (!config) {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
            return DTU_ERROR;
        }

        char json_response[1024];
        snprintf(json_response, sizeof(json_response),
                 "{"
                 "\"device_id\":\"%s\","
                 "\"serial_number\":\"%s\","
                 "\"model\":%d,"
                 "\"firmware_version\":\"%s\","
                 "\"hardware_version\":\"%s\""
                 "}",
                 config->device_info.device_id,
                 config->device_info.serial_number,
                 config->device_info.model,
                 config->device_info.firmware_version,
                 config->device_info.hardware_version);

        dtu_web_set_json_response(response, json_response);
        return DTU_OK;

    } else if (request->method == HTTP_METHOD_POST) {
        /* 更新系统设置 */
        if (request->body_length == 0 || request->body[0] == '\0') {
            dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing request body");
            return DTU_ERROR;
        }

        /* 解析系统设置 */
        char* device_id = get_json_string_value(request->body, "device_id");
        char* serial_number = get_json_string_value(request->body, "serial_number");

        /* 更新配置 */
        dtu_config_t* config = (dtu_config_t*)dtu_config_get();
        if (config) {
            if (device_id) {
                DTU_STRNCPY(config->device_info.device_id, device_id, sizeof(config->device_info.device_id));
                DTU_FREE(device_id);
            }
            if (serial_number) {
                DTU_STRNCPY(config->device_info.serial_number, serial_number, sizeof(config->device_info.serial_number));
                DTU_FREE(serial_number);
            }

            /* 保存配置 */
            dtu_config_save();
        }

        dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"System configuration updated\"}");
        return DTU_OK;
    }

    dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
    return DTU_ERROR;
}

/* Modbus设备配置API处理函数 */
static dtu_error_t api_modbus_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method == HTTP_METHOD_GET) {
        /* 返回Modbus设备配置 */
        const dtu_config_t* config = dtu_config_get();
        if (!config) {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
            return DTU_ERROR;
        }

        char json_response[4096];
        int pos = 0;
        int remaining = sizeof(json_response) - 1;

        pos += snprintf(json_response + pos, remaining - pos,
                       "{\"device_count\":%d,\"devices\":[",
                       config->modbus_config.device_count);

        for (int i = 0; i < config->modbus_config.device_count && i < 16; i++) {
            pos += snprintf(json_response + pos, remaining - pos,
                           "%s{\"id\":%d,\"name\":\"%s\",\"enabled\":%s,\"crc_enable\":%s,"
                           "\"poll_string\":\"%s\",\"serial_port\":\"%s\",\"description\":\"%s\"}",
                           (i > 0) ? "," : "",
                           config->modbus_config.devices[i].id,
                           config->modbus_config.devices[i].name,
                           config->modbus_config.devices[i].enabled ? "true" : "false",
                           config->modbus_config.devices[i].crc_enable ? "true" : "false",
                           config->modbus_config.devices[i].poll_string,
                           config->modbus_config.devices[i].serial_port,
                           config->modbus_config.devices[i].description);
        }

        pos += snprintf(json_response + pos, remaining - pos, "]}");

        dtu_web_set_json_response(response, json_response);
        return DTU_OK;

    } else if (request->method == HTTP_METHOD_POST) {
        /* 保存Modbus设备配置 */
        if (request->body_length == 0 || request->body[0] == '\0') {
            dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing request body");
            return DTU_ERROR;
        }

        /* 解析Modbus配置 */
        int device_id = get_json_int_value(request->body, "id", 1);
        char* name = get_json_string_value(request->body, "name");
        int address = get_json_int_value(request->body, "address", 1);
        int function_code = get_json_int_value(request->body, "function_code", 3);
        int start_address = get_json_int_value(request->body, "start_address", 0);
        int count = get_json_int_value(request->body, "count", 10);
        char* serial_port = get_json_string_value(request->body, "serial_port");
        bool enabled = get_json_bool_value(request->body, "enabled", true);
        char* collect_string = get_json_string_value(request->body, "collect_string");

        /* 更新配置 */
        dtu_config_t* config = (dtu_config_t*)dtu_config_get();
        if (config) {
            /* 查找或创建设备配置 */
            int device_index = -1;
            for (int i = 0; i < config->modbus_config.device_count; i++) {
                if (config->modbus_config.devices[i].id == device_id) {
                    device_index = i;
                    break;
                }
            }

            /* 如果没找到且还有空间，创建新设备 */
            if (device_index == -1 && config->modbus_config.device_count < 16) {
                device_index = config->modbus_config.device_count;
                config->modbus_config.device_count++;
            }

            if (device_index >= 0) {
                config->modbus_config.devices[device_index].id = device_id;
                if (name) {
                    DTU_STRNCPY(config->modbus_config.devices[device_index].name, name,
                               sizeof(config->modbus_config.devices[device_index].name));
                }
                /* TODO: 更新为新的配置结构 */
                config->modbus_config.devices[device_index].enabled = enabled;
                if (serial_port) {
                    DTU_STRNCPY(config->modbus_config.devices[device_index].serial_port, serial_port,
                               sizeof(config->modbus_config.devices[device_index].serial_port));
                }
                /* 暂时使用默认的轮询字符串 */
                DTU_STRNCPY(config->modbus_config.devices[device_index].poll_string, "010300000001",
                           sizeof(config->modbus_config.devices[device_index].poll_string));
                config->modbus_config.devices[device_index].crc_enable = true;

                /* 保存配置 */
                dtu_config_save();
            }
        }

        /* 释放内存 */
        if (name) DTU_FREE(name);
        if (serial_port) DTU_FREE(serial_port);
        if (collect_string) DTU_FREE(collect_string);

        dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"Modbus configuration saved\"}");
        return DTU_OK;
    }

    dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
    return DTU_ERROR;
}

/* Modbus测试API处理函数 */
static dtu_error_t api_modbus_test_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method == HTTP_METHOD_POST) {
        if (request->body_length == 0 || request->body[0] == '\0') {
            dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing request body");
            return DTU_ERROR;
        }

        /* 解析测试参数 */
        int address = get_json_int_value(request->body, "address", 1);
        int function_code = get_json_int_value(request->body, "function_code", 3);
        int start_address = get_json_int_value(request->body, "start_address", 0);
        int count = get_json_int_value(request->body, "count", 10);
        char* serial_port = get_json_string_value(request->body, "serial_port");

        /* 执行真实的Modbus测试 */
        char json_response[2048];

        /* 如果没有指定串口，从配置中获取 */
        if (!serial_port || strlen(serial_port) == 0) {
            const dtu_config_t* config = dtu_config_get();
            if (config && config->modbus_config.device_count > 0) {
                serial_port = DTU_MALLOC(strlen(config->modbus_config.devices[0].serial_port) + 1);
                if (serial_port) {
                    strcpy(serial_port, config->modbus_config.devices[0].serial_port);
                }
            }
        }

        /* 获取串口配置 */
        const dtu_config_t* config = dtu_config_get();
        const char* device_path = NULL;
        int baudrate = 9600;

        if (config) {
            if (serial_port && strcmp(serial_port, "rs485") == 0) {
                device_path = config->rs485_config.device;
                baudrate = config->rs485_config.baudrate;
            } else if (serial_port && strcmp(serial_port, "rs232") == 0) {
                device_path = config->rs232_config.device;
                baudrate = config->rs232_config.baudrate;
            } else {
                device_path = config->rs485_config.device;
                baudrate = config->rs485_config.baudrate;
            }
        }

        /* 尝试进行真实的Modbus通信 */
        uint16_t values[32] = {0};
        bool test_success = false;
        char error_msg[256] = "";

        if (device_path && strlen(device_path) > 0) {
            /* 创建临时的串口配置 */
            serial_config_t temp_serial_config = {0};
            DTU_STRNCPY(temp_serial_config.device, device_path, sizeof(temp_serial_config.device));
            temp_serial_config.baudrate = baudrate;
            temp_serial_config.databits = config ? config->rs485_config.databits : 8;
            temp_serial_config.stopbits = config ? config->rs485_config.stopbits : 1;
            temp_serial_config.parity = config ? config->rs485_config.parity : 'N';
            temp_serial_config.timeout = config ? config->rs485_config.timeout : 1000;

            /* 创建临时的Modbus上下文 */
            modbus_context_t* temp_ctx = dtu_modbus_init(MODBUS_MODE_RTU, &temp_serial_config);
            if (temp_ctx) {
                /* 连接设备 */
                if (dtu_modbus_connect(temp_ctx) == DTU_OK) {
                    /* 设置从站地址 */
                    dtu_modbus_set_slave_id(temp_ctx, (uint8_t)address);
                    dtu_modbus_set_response_timeout(temp_ctx, 3000); /* 3秒超时 */

                    /* 根据功能码读取数据 */
                    dtu_error_t result = DTU_ERROR;
                    if (function_code == 3) {
                        /* 读保持寄存器 */
                        result = dtu_modbus_read_holding_registers(temp_ctx, (uint8_t)address,
                                                                 (uint16_t)start_address,
                                                                 (uint16_t)count, values);
                    } else if (function_code == 4) {
                        /* 读输入寄存器 */
                        result = dtu_modbus_read_input_registers(temp_ctx, (uint8_t)address,
                                                               (uint16_t)start_address,
                                                               (uint16_t)count, values);
                    } else {
                        snprintf(error_msg, sizeof(error_msg), "Unsupported function code: %d", function_code);
                    }

                    if (result == DTU_OK) {
                        test_success = true;
                    } else {
                        snprintf(error_msg, sizeof(error_msg), "Modbus read failed, error code: %d", result);
                    }

                    /* 断开连接 */
                    dtu_modbus_disconnect(temp_ctx);
                } else {
                    snprintf(error_msg, sizeof(error_msg), "Failed to connect to device: %s", device_path);
                }

                /* 清理资源 */
                dtu_modbus_cleanup(temp_ctx);
            } else {
                snprintf(error_msg, sizeof(error_msg), "Failed to initialize Modbus context");
            }
        } else {
            snprintf(error_msg, sizeof(error_msg), "No device configured for %s",
                    serial_port ? serial_port : "unknown");
        }

        /* 构建响应 */
        if (test_success) {
            int pos = snprintf(json_response, sizeof(json_response),
                             "{"
                             "\"result\":\"success\","
                             "\"message\":\"Modbus test completed successfully\","
                             "\"data\":{"
                             "\"address\":%d,"
                             "\"function_code\":%d,"
                             "\"start_address\":%d,"
                             "\"count\":%d,"
                             "\"serial_port\":\"%s\","
                             "\"device_path\":\"%s\","
                             "\"baudrate\":%d,"
                             "\"status\":\"connected\","
                             "\"values\":[",
                             address, function_code, start_address, count,
                             serial_port ? serial_port : "rs485",
                             device_path ? device_path : "unknown",
                             baudrate);

            for (int i = 0; i < count && i < 32; i++) {
                pos += snprintf(json_response + pos, sizeof(json_response) - pos,
                               "%s%d", (i > 0) ? "," : "", values[i]);
            }

            pos += snprintf(json_response + pos, sizeof(json_response) - pos,
                           "],"
                           "\"timestamp\":%ld"
                           "}"
                           "}",
                           time(NULL));
        } else {
            snprintf(json_response, sizeof(json_response),
                     "{"
                     "\"result\":\"error\","
                     "\"message\":\"Modbus test failed: %s\","
                     "\"data\":{"
                     "\"address\":%d,"
                     "\"function_code\":%d,"
                     "\"start_address\":%d,"
                     "\"count\":%d,"
                     "\"serial_port\":\"%s\","
                     "\"device_path\":\"%s\","
                     "\"baudrate\":%d,"
                     "\"status\":\"error\","
                     "\"timestamp\":%ld"
                     "}"
                     "}",
                     error_msg,
                     address, function_code, start_address, count,
                     serial_port ? serial_port : "rs485",
                     device_path ? device_path : "unknown",
                     baudrate,
                     time(NULL));
        }

        if (serial_port) {
            DTU_FREE(serial_port);
        }

        dtu_web_set_json_response(response, json_response);
        return DTU_OK;
    }

    dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
    return DTU_ERROR;
}

/* AT命令执行API处理函数 */
static dtu_error_t api_at_command_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method == HTTP_METHOD_POST) {
        if (request->body_length == 0 || request->body[0] == '\0') {
            dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing request body");
            return DTU_ERROR;
        }

        /* 解析JSON请求 */
        char* command = get_json_string_value(request->body, "command");
        if (!command) {
            dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing command parameter");
            return DTU_ERROR;
        }

        DTU_LOG_INFO("Executing AT command: %s", command);

        /* 执行AT命令 */
        at_cmd_response_t at_response = {0};
        dtu_error_t result = dtu_at_execute(command, &at_response);

        /* 构建JSON响应 */
        char json_response[4096];  /* 增大缓冲区以容纳转义后的内容 */
        if (result == DTU_OK && at_response.result == AT_RESULT_OK) {
            /* 对AT响应进行JSON转义 */
            char escaped_response[2048];
            json_escape_string(at_response.response[0] ? at_response.response : "OK",
                              escaped_response, sizeof(escaped_response));

            snprintf(json_response, sizeof(json_response),
                    "{"
                    "\"success\": true,"
                    "\"response\": \"%s\""
                    "}", escaped_response);
        } else {
            const char* error_msg = "Command execution failed";
            if (at_response.result == AT_RESULT_INVALID) {
                error_msg = "Invalid command";
            } else if (at_response.result == AT_RESULT_TIMEOUT) {
                error_msg = "Command timeout";
            } else if (at_response.result == AT_RESULT_BUSY) {
                error_msg = "System busy";
            }

            snprintf(json_response, sizeof(json_response),
                    "{"
                    "\"success\": false,"
                    "\"error\": \"%s\""
                    "}", error_msg);
        }

        free(command);
        dtu_web_set_json_response(response, json_response);
        return DTU_OK;
    }

    dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
    return DTU_ERROR;
}

/* Modbus测试配置API处理函数 */
static dtu_error_t api_modbus_test_config_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method == HTTP_METHOD_GET) {
        /* 返回Modbus测试配置 */
        const dtu_config_t* config = dtu_config_get();
        if (!config) {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
            return DTU_ERROR;
        }

        char json_response[1024];
        snprintf(json_response, sizeof(json_response),
                "{"
                "\"device_address\":%d,"
                "\"function_code\":%d,"
                "\"start_address\":%d,"
                "\"register_count\":%d,"
                "\"serial_port\":\"%s\""
                "}",
                config->modbus_test_config.device_address,
                config->modbus_test_config.function_code,
                config->modbus_test_config.start_address,
                config->modbus_test_config.register_count,
                config->modbus_test_config.serial_port);

        dtu_web_set_json_response(response, json_response);
        return DTU_OK;

    } else if (request->method == HTTP_METHOD_POST) {
        /* 保存Modbus测试配置 */
        if (request->body_length == 0 || request->body[0] == '\0') {
            dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing request body");
            return DTU_ERROR;
        }

        /* 解析测试配置 */
        int device_address = get_json_int_value(request->body, "device_address", 1);
        int function_code = get_json_int_value(request->body, "function_code", 3);
        int start_address = get_json_int_value(request->body, "start_address", 3);
        int register_count = get_json_int_value(request->body, "register_count", 1);
        char* serial_port = get_json_string_value(request->body, "serial_port");

        /* 更新配置 */
        dtu_config_t* config = (dtu_config_t*)dtu_config_get();
        if (!config) {
            if (serial_port) free(serial_port);
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
            return DTU_ERROR;
        }

        config->modbus_test_config.device_address = device_address;
        config->modbus_test_config.function_code = function_code;
        config->modbus_test_config.start_address = start_address;
        config->modbus_test_config.register_count = register_count;

        if (serial_port) {
            DTU_STRNCPY(config->modbus_test_config.serial_port, serial_port,
                       sizeof(config->modbus_test_config.serial_port));
            free(serial_port);
        }

        /* 保存配置到文件 */
        if (dtu_config_save() != DTU_OK) {
            dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to save configuration");
            return DTU_ERROR;
        }

        DTU_LOG_INFO("Modbus test configuration updated: addr=%d, func=%d, start=%d, count=%d, port=%s",
                     device_address, function_code, start_address, register_count,
                     config->modbus_test_config.serial_port);

        dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"Modbus test configuration updated\"}");
        return DTU_OK;
    }

    dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
    return DTU_ERROR;
}

/* JSON字符串转义函数 */
static void json_escape_string(const char* input, char* output, size_t output_size)
{
    if (!input || !output || output_size == 0) {
        if (output && output_size > 0) {
            output[0] = '\0';
        }
        return;
    }

    size_t output_pos = 0;
    const char* p = input;

    while (*p && output_pos < output_size - 1) {
        switch (*p) {
            case '"':
                if (output_pos < output_size - 2) {
                    output[output_pos++] = '\\';
                    output[output_pos++] = '"';
                }
                break;
            case '\\':
                if (output_pos < output_size - 2) {
                    output[output_pos++] = '\\';
                    output[output_pos++] = '\\';
                }
                break;
            case '\r':
                if (output_pos < output_size - 2) {
                    output[output_pos++] = '\\';
                    output[output_pos++] = 'r';
                }
                break;
            case '\n':
                if (output_pos < output_size - 2) {
                    output[output_pos++] = '\\';
                    output[output_pos++] = 'n';
                }
                break;
            case '\t':
                if (output_pos < output_size - 2) {
                    output[output_pos++] = '\\';
                    output[output_pos++] = 't';
                }
                break;
            default:
                output[output_pos++] = *p;
                break;
        }
        p++;
    }

    output[output_pos] = '\0';
}

/* 系统信息API处理函数 */
static dtu_error_t api_system_info_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)request;
    (void)user_data;

    const dtu_config_t* config = dtu_config_get();
    if (!config) {
        dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to get configuration");
        return DTU_ERROR;
    }

    /* 返回系统信息 */
    char json_response[1024];
    snprintf(json_response, sizeof(json_response),
             "{"
             "\"device_id\":\"%s\","
             "\"device_model\":\"%s\","
             "\"serial_number\":\"%s\","
             "\"firmware_version\":\"%s\","
             "\"hardware_version\":\"%s\","
             "\"build_version\":\"%s\","
             "\"uptime\":\"%s\","
             "\"system_time\":\"%s\""
             "}",
             config->device_info.device_id,
             config->device_info.model == 1 ? "Ethernet" :
                (config->device_info.model == 2 ? "WiFi+Ethernet" : "4G+Ethernet"),
             config->device_info.serial_number,
             config->device_info.firmware_version,
             config->device_info.hardware_version,
             config->device_info.model == 1 ? "ethernet" :
                (config->device_info.model == 2 ? "wifi" : "4g"),
             "1天2小时30分钟",  /* 系统运行时间，实际应从系统获取 */
             "2023-01-01 12:00:00"  /* 系统时间，实际应从系统获取 */
             );

    dtu_web_set_json_response(response, json_response);
    return DTU_OK;
}

/* 保存配置API处理函数 */
static dtu_error_t api_system_save_config_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)request;
    (void)user_data;

    /* 保存配置到文件 */
    dtu_error_t ret = dtu_config_save();
    if (ret == DTU_OK) {
        dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"Configuration saved successfully\"}");
    } else {
        dtu_web_set_error_response(response, HTTP_STATUS_INTERNAL_ERROR, "Failed to save configuration");
    }

    return DTU_OK;
}

/* 清除日志API处理函数 */
static dtu_error_t api_system_clear_logs_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)request;
    (void)user_data;

    /* 清除系统日志 - 这里应该实现日志文件清除功能 */
    /* dtu_log_clear(); */  /* 函数不存在，需要实现或使用其他方式 */

    dtu_web_set_json_response(response, "{\"result\":\"success\",\"message\":\"System logs cleared successfully\"}");
    return DTU_OK;
}

/* 系统检查API处理函数 */
static dtu_error_t api_system_check_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)request;
    (void)user_data;

    /* 执行系统检查 */
    char check_result[512];
    snprintf(check_result, sizeof(check_result),
             "系统检查完成：\\n"
             "- 配置文件：正常\\n"
             "- 网络连接：正常\\n"
             "- 串口状态：正常\\n"
             "- 存储空间：正常\\n"
             "- 内存使用：正常");

    char json_response[1024];
    snprintf(json_response, sizeof(json_response),
             "{\"result\":\"success\",\"message\":\"%s\"}",
             check_result);

    dtu_web_set_json_response(response, json_response);
    return DTU_OK;
}

/* 串口测试API处理函数 */
static dtu_error_t api_serial_test_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)user_data;

    if (request->method != HTTP_METHOD_POST) {
        dtu_web_set_error_response(response, HTTP_STATUS_METHOD_NOT_ALLOWED, "Method not allowed");
        return DTU_ERROR;
    }

    if (request->body_length == 0 || request->body[0] == '\0') {
        dtu_web_set_error_response(response, HTTP_STATUS_BAD_REQUEST, "Missing request body");
        return DTU_ERROR;
    }

    /* 解析测试参数 */
    char* serial_type = get_json_string_value(request->body, "serial_type");
    char* device = get_json_string_value(request->body, "device");
    int baudrate = get_json_int_value(request->body, "baudrate", 9600);
    int databits = get_json_int_value(request->body, "databits", 8);
    int stopbits = get_json_int_value(request->body, "stopbits", 1);
    char* parity = get_json_string_value(request->body, "parity");

    /* 执行串口测试 */
    bool test_success = true;  /* 这里应该调用实际的串口测试函数 */

    char json_response[512];
    if (test_success) {
        snprintf(json_response, sizeof(json_response),
                 "{\"success\":true,\"message\":\"%s串口测试成功\"}",
                 serial_type ? serial_type : "");
    } else {
        snprintf(json_response, sizeof(json_response),
                 "{\"success\":false,\"error\":\"%s串口测试失败\"}",
                 serial_type ? serial_type : "");
    }

    /* 释放内存 */
    if (serial_type) DTU_FREE(serial_type);
    if (device) DTU_FREE(device);
    if (parity) DTU_FREE(parity);

    dtu_web_set_json_response(response, json_response);
    return DTU_OK;
}

/* 推送连接测试API处理函数 */
static dtu_error_t api_push_test_connection_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)request;
    (void)user_data;

    /* 执行推送连接测试 */
    bool test_success = true;  /* 这里应该调用实际的推送连接测试函数 */

    char json_response[256];
    if (test_success) {
        snprintf(json_response, sizeof(json_response),
                 "{\"success\":true,\"message\":\"推送连接测试成功\"}");
    } else {
        snprintf(json_response, sizeof(json_response),
                 "{\"success\":false,\"error\":\"推送连接测试失败\"}");
    }

    dtu_web_set_json_response(response, json_response);
    return DTU_OK;
}

/* 推送数据测试API处理函数 */
static dtu_error_t api_push_test_data_handler(const http_request_t* request, http_response_t* response, void* user_data)
{
    (void)request;
    (void)user_data;

    /* 执行推送数据测试 */
    bool test_success = true;  /* 这里应该调用实际的推送数据测试函数 */

    char json_response[256];
    if (test_success) {
        snprintf(json_response, sizeof(json_response),
                 "{\"success\":true,\"message\":\"推送数据测试成功\"}");
    } else {
        snprintf(json_response, sizeof(json_response),
                 "{\"success\":false,\"error\":\"推送数据测试失败\"}");
    }

    dtu_web_set_json_response(response, json_response);
    return DTU_OK;
}
